/*+***********************************************************************************
 Filename: regfile.v
 Description: a simple register-files implementation.

 Modification:
   2022.10.14 Creation   H.Zheng

Copyright (C) 2022  Zheng Hui (hzheng@gzhu.edu.cn)

License: MulanPSL-2.0

Acknowledge: Thanks to Hu Jinbo, learned the implementation from his E203 Humingbird project source. 
***********************************************************************************-*/

module regfile (
  input reset_n,

  input [4:0] i_rf_rs1idx,
  input [4:0] i_rf_rs2idx,
  output  [31:0] rf_rs1data,
  output  [31:0] rf_rs2data,

  output  [31:0] x16_value,

  input [4:0] i_rf_rdidx,
  input i_rf_rdwen,
  input [31:0] i_rf_rd_data,
  input i_rf_rd_wr_clk  //update rf[i_rf_rdidx] with i_rf_rd_data on posedge of i_rf_rd_wr_clk if (i_rf_rdwen == 1)

);

reg [31:0] rf_r [1:31];
wire rf_wen[1:31];


  genvar i;
  generate
  
      for (i=1; i<32; i=i+1) begin:regfile
  
        assign rf_wen[i] = i_rf_rdwen & (i_rf_rdidx == i) ;
        always @(posedge i_rf_rd_wr_clk or negedge reset_n) begin
            if (~reset_n) begin
                rf_r[i] <= 0;
            end
            else if (rf_wen[i]) begin
                rf_r[i] <= i_rf_rd_data;
            end
        end
  
      end
  endgenerate

assign rf_rs1data = (i_rf_rs1idx > 0) ? rf_r[i_rf_rs1idx] : 32'b0;
assign rf_rs2data = (i_rf_rs2idx > 0) ? rf_r[i_rf_rs2idx] : 32'b0;

assign x16_value = rf_r[16];

endmodule


